import * as localforage from "localforage";

console.log("[SW] Push worker started");

self.onpush = (event) => {
  console.log("[SW] push data: ", event.data);
  const data = event.data.json().notification;
  if (data.type.startsWith("m.call")) {
    let title;
    let sender = data.sender_display_name || data.sender;
    if (sender) {
      title = `Call from ${sender}`;
    } else {
      title = "Call";
    }
    // We don't check for permission since we have `desktop-notification` in manifest.webapp
    let timeoutID = self.setTimeout(() => {
      self.registration
        .getNotifications({ tag: timeoutID.toString() })
        .then((notifList) => {
          for (let notif of notifList) {
            if (notif.tag === timeoutID.toString()) notif.close();
          }
        });
    }, data.content.lifetime || 60000);
    self.registration.showNotification(title, {
      body: "You have a voice call" + sender ? ` from ${sender}` : "",
      dir: "auto",
      vibrate: [200, 100, 200, 100],
      data: data,
      tag: timeoutID.toString(),
      actions: [
        {
          action: "accept",
          title: "Accept",
        },
        {
          action: "reject",
          title: "Reject",
        },
      ],
    });
  } else {
    // TODO: show notification for the message
  }
};

self.onnotificationclick = (evt) => {
  evt.notification.close();
  self.clearTimeout(parseInt(evt.notification.tag));
  if (evt.action === "accept") {
    evt
      .waitUntil(
        clients.matchAll({
          type: "window",
        })
      )
      .then((clientList) => {
        for (let client of clientList) {
          if (client.url === "/" && client.focus) {
            return client.focus();
          }
        }
        if (clients.openWindow) {
          return clients.openWindow("/#call");
        }

        if (clients.openApp) {
          return clients.openApp();
        }
      })
      .catch((error) => {
        console.error("[SW] ERROR NOTIF:", error);
      });
  }
};

self.onpushsubscriptionchange = (evt) => {
  console.log("[SW] Subscription expired");
  event.waitUntil(
    self.registration.pushManager
      .subscribe({ userVisibleOnly: true })
      .then((subscr) => {
        localforage.getItem("login").then((login) => {
          localforage.getItem("pushgateway").then((pushGateway) => {
            const endpoint =
              login.well_known["m.homeserver"].base_url +
              "/_matrix/client/r0/pushers/set?access_token=" +
              login.access_token;
            const data = {
              pushkey: subscr.endpoint,
              kind: "http",
              app_id: "ir.minetest.katrix",
              data: { url: pushGateway, format: "event_id_only" },
              app_display_name: "Katrix",
              device_display_name: "KaiOS",
              lang: "en",
            };
            let xhr = new XMLHttpRequest({ mozSystem: true });
            xhr.open("POST", endpoint);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify(data));
          });
        });
      })
  );
};
